import { src, dest } from 'gulp'
import plumber from 'gulp-plumber'  // 意外处理，避免意外导致gulp watch 失效中断  参考链接: http://kejyun.github.io/gulp-learning-notes/plguins/Tool/Plugins-Tool-gulp-plumber.html
import data from 'gulp-data'
import ejs from 'gulp-ejs'
import rename from 'gulp-rename'
import replace from 'gulp-replace'
import path from 'path'
import fs from 'fs'

import Config from '../config'

const getHtmlData = function(file) {
  let htmlDir = path.join(Config.root, Config.html.path)  // 存放html模板的文件目录
  let htmlDataDir = path.join(Config.root, Config.html.dataPath)  // 存放html模板数据的文件目录
  let fileDir = path.dirname(file.path) // html模板的文件目录
  let dataFileName = `${path.basename(file.path, '.ejs')}${Config.html.dataExt}` // html模板数据的文件名(含后缀)
  let dataFileDir = fileDir.replace(htmlDir, htmlDataDir) // html模板数据的文件目录
  let dataFilePath = path.join(dataFileDir, dataFileName) // html模板数据的文件路径
  if(fs.existsSync(dataFilePath)) {
    return JSON.parse(fs.readFileSync(dataFilePath))
  }
  return {}
}

class Html {
  static build() {
    return src(Config.html.src)
      .pipe(plumber(Config.plumber))
      .pipe(data(getHtmlData))
      .pipe(ejs({}, {}))
      .pipe(replace('/frontend/', './'))  // 添加/frontend字符前缀为了之后的资源代理
      .pipe(rename({ extname: '.html' }))
      .pipe(dest(Config.html.dest))
  }
}

export default Html